#coding:utf-8
import json
from identify_items import get_items_from_image
import os

class Member():
    def __init__(self, name):
        self.name = name
        self.gain = 0
        self.package = {}

    def obtain_one_item(self, item):
        self.gain += item.price
        if item.name in self.package.keys():
            self.package[item.name] += 1
        else:
            self.package[item.name] = 1

    def __str__(self):
        return "{\"%s\": {\"总价\": %r, \"物品详情\": %r}}" % (self.name, self.gain, self.package)

class Item():
    def __init__(self, name, amount=0, price=0):
        self.name = name
        self.price = price
        self.amount = amount

    def delete_one(self):
        if self.amount > 0:
            self.amount -= 1
        return self.amount

    def add_one(self):
        self.amount += 1

    def __str__(self):
        return "{\"名称\": \"%s\", \"价格\": %d, \"数量\": %d}" % (self.name, self.price, self.amount)

def mapping_price(items_table, price_table):
    item_list = []
    for item_name, amount in items_table.items():
        new_item = Item(item_name, amount=amount)
        for item_full_name, price in price_table.items():
            if item_full_name.startswith(item_name):
                new_item.name = item_full_name
                new_item.price = price
                break
        if new_item.price > 0:
            item_list.append(new_item)
        else:
            # raise ValueError("请设置 %s 的价格！" % item_name)
            print("请设置 %s 的价格！" % item_name)
    return item_list

def distribute_items(member_list, item_list):
    sell_item_list = []
    with open("sell.json") as fd:
        sell_item_list = json.load(fd)
    ISK = Item("isk", price=10000)
    item_list.append(ISK)
    total_sell_price = 0
    while item_list:
        member_list = sorted(member_list, key=lambda member: member.gain, reverse=False)
        item_list = sorted(item_list, key=lambda item: item.price, reverse=True)
        is_sell = False
        for sell_item in sell_item_list:
            if sell_item.startswith(item_list[0].name):
                ISK.amount += int(item_list[0].price * 0.75 / 10000)
                is_sell = True
        if not item_list[0].delete_one():
            print("%s 已经分配完毕" % item_list[0].name)
            del item_list[0]
        else:
            if not is_sell:
                member_list[0].obtain_one_item(item_list[0])
    # member_gain_isk = total_sell_price*0.75/member_list.__len__()
    # for member in member_list:
    #     member.package["isk"] = member_gain_isk
    return member_list

def check_repeat(old_items, new_items):
    if old_items.__len__() == 8:
        for i in range(new_items.__len__()):
            if old_items[4:] == new_items[i: i + 4]:
                old_items = old_items[:4]
    if old_items.__len__() > 4:
        for i in range(new_items.__len__()):
            if old_items[:4] == new_items[i: i + 4]:
                if old_items.__len__() > 4:
                    old_items = old_items[4:]
                else:
                    old_items = []

    return old_items


def count_all_items(picture_list):
    items_list = []
    for picture in picture_list:
        print("deal picture %s" % picture)
        current_items = get_items_from_image(picture)
        print(current_items)
        if items_list.__len__() >= 8:
            current_items = check_repeat(current_items, items_list)
        items_list += current_items
    items_dict = {}
    for item in items_list:
        if item[0] in items_dict.keys():
            items_dict[item[0]] += int(item[1])
        else:
            items_dict[item[0]] = int(item[1])
    return items_dict

def main(reload=True):
    if reload:
        picture_list = []
        for _, _, files in os.walk("./gain"):
            for file in files:
                if file.endswith(".jpg"):
                    picture_list.append("./gain/" + file)
        print(picture_list)
        all_items = count_all_items(picture_list)
        print(all_items)
        price_table = {}
        with open("price.json", "r") as fd:
            price_table = json.load(fd)
        item_list = mapping_price(all_items, price_table)
        with open("items.json", "w+") as fd:
            fd.write("[\n")
            for i in range(item_list.__len__()):
                fd.write("%s%s\n" % (item_list[i], "" if i == item_list.__len__()-1 else ","))
            fd.write("]\n")
    else:
        item_list = []
        with open("items.json", "r") as fd:
            json_list = json.load(fd)
            for i in json_list:
                item_list.append(Item(i["名称"], i["数量"], i["价格"]))
    member_list = []
    with open("member.json", "r") as fd:
        member_name_list = json.load(fd)
    for member_name in member_name_list:
        member_list.append(Member(member_name))
    result = distribute_items(member_list, item_list)
    for member in result:
        print(member)

if __name__ == '__main__':
    main(reload=False)